package com.example.xd.Contorller;

import com.example.xd.DAO.userMapper;
import com.example.xd.Entity.User;
import com.example.xd.Entity.Video;
import com.example.xd.Service.RegisterService;
import com.example.xd.Service.VideoUploadService;
import com.example.xd.Util.VideoDurationUtil;
import com.example.xd.Util.jwtUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ssl.SslProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.sun.tools.attach.VirtualMachine.list;

@RestController
@RequestMapping("/user")
public class userController {

    @Resource
    private jwtUtil jwtUtil;


    private final userMapper userMapper;
    private final RegisterService registerService;
    private final VideoUploadService videoUploadService;
    private final VideoDurationUtil videoDurationUtil;

    @Autowired
    public userController(userMapper userMapper, RegisterService registerService, VideoUploadService videoUploadService, VideoDurationUtil videoDurationUtil) {
        this.userMapper = userMapper;
        this.registerService = registerService;
        this.videoUploadService = videoUploadService;
        this.videoDurationUtil = videoDurationUtil;
    }


    private static final String FILE_PATH = "D:" + File.separator + "fgobb" + File.separator + "uploaded_images";

    private static final String notLoginImage = "D:" + File.separator + "fgobb" + File.separator + "uploaded_images" + File.separator + "66666.jpg";


    //注册
    @PostMapping(value = "/register")
    public ResponseEntity<String> uploadUser(
            @RequestParam("name") String userName,
            @RequestParam("password") String password,
            @RequestParam("email") String userEmail,
            @RequestParam("registerTime") String createTimeStr) {

        // 检查数据是否为空字符串
        if (userName.isEmpty() || password.isEmpty() || userEmail.isEmpty()) {
            return ResponseEntity.ofNullable("数据不能为空");
        }

        LocalDateTime createTime = null;
        if (createTimeStr != null && !createTimeStr.isEmpty()) {
            // 将字符串格式的时间转换为LocalDateTime
            createTime = LocalDateTime.parse(createTimeStr, DateTimeFormatter.ISO_DATE_TIME);
        }

        User user = new User();
        user.setName(userName);
        user.setPassword(password);
        user.setEmail(userEmail);
        user.setRegisterTime(createTime);

        if (registerService.isUserExist(user) == false) {
            return ResponseEntity.ofNullable("用户已存在");
        }

        user.setImageUrl(FILE_PATH);

        userMapper.InsertUser(user);

        String userID = String.valueOf(userMapper.SelectUserIdByEmail(userEmail));
        return ResponseEntity.ok(userID);
    }


    //用户登录
    @PostMapping("/login")
    public ResponseEntity<?> Login(User user) {
        String userEmail = user.getEmail();
        String password = user.getPassword();

        if (userEmail.isEmpty() || password.isEmpty()) {
            return ResponseEntity.ofNullable("请输入账号或者密码");
        }

//用户未注册逻辑（可选）

        if (userMapper.selectUser(userEmail, password) == null) {
            return ResponseEntity.ok("用户名或密码错误");
        }

        String token = jwtUtil.generateToken(userEmail);
        return ResponseEntity.ok(token);
    }

    //调取用户头像
    @PostMapping("/getImage")
    public ResponseEntity<String> getImage(@RequestHeader("Authorization") String authorizationHeader) {


        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            if (jwtUtil.validateToken(token)) {
                // 从token中正确获取email
                String email = jwtUtil.getUserEmailFromToken(token);
                String userImage = userMapper.selectUserImage(email);
                return ResponseEntity.ok(userImage);

            }
        }
        return ResponseEntity.ok(notLoginImage);
//    return userMapper.selectUserImage("123");
    }

    // 定义允许上传的文件格式列表,可以判定上传的文件是否符合规则（保留）
    private static final List<String> ALLOWED_FORMATS = Arrays.asList("mp4", "avi", "mov", "jpg", "png", "jpeg", "gif");
//
//    //视频上传
//    @PostMapping("/uploadVideo")
//    public ResponseEntity<String> uploadVideo(@RequestHeader("Authorization") String authorizationHeader,
//                                              @RequestParam("videoByte") MultipartFile videoByte,
//                                              @RequestParam("videoImage") MultipartFile videoImage,
//                                              Video video) throws IOException {
//        // 验证授权信息是否合法并获取用户相关信息
//        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
//            String token = authorizationHeader.substring(7);
//
//            if (jwtUtil.validateToken(token)) {
//                String email = jwtUtil.getUserEmailFromToken(token);
//                int userId = userMapper.selectUserID(email);
//                video.setUserId(userId);
//
//                try {
//                    // 获取视频字节数据和原始文件名
//                    byte[] videoData = videoByte.getBytes();
//                    String OriginalFilename = videoByte.getOriginalFilename();
////                    获取文件后缀名
//                    String FileExtension = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
//
//                    //获取用户输入的文件名
//                    String GetVideoName = video.getName();
//
////添加加视频文件重名判定
//                    if (videoUploadService.getVideoNameCount(GetVideoName + FileExtension) == true) {
//
//                        //将后缀和文件名连接
//                        String videoName = GetVideoName + FileExtension;
////定义系统时间，写入图片名称不会冲突
//                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//
//                        String VideoFileExtension = videoImage.getOriginalFilename().substring(videoImage.getOriginalFilename().lastIndexOf("."));
//                        String videoImageName = simpleDateFormat + VideoFileExtension;
//
//                        // 设置视频相关属性
//                        video.setName(videoName);
//                        video.setVideoUrl(video.getPath() + File.separator + videoName);
//
//
//                        // 上传视频文件
//                        videoUploadService.uploadVideo(videoData, videoName);
//
//                        // 上传视频图片文件，优化异常处理逻辑
//                        videoUploadService.uploadVideoImage(videoImage, videoImageName);
//
//                        // 获取视频时长
//                        double videoTime = videoDurationUtil.getVideoDuration(video.getPath() + File.separator + videoName);
//                        System.out.println(videoTime);
//                        video.setDuration((int) videoTime);
//
//                        video.setThumbUrl(videoUploadService.videoImage_PATH + File.separator + videoImageName);
//
//                        // 将视频信息插入数据库
//                        userMapper.InsertVideo(video);
//
//                        // 文件上传成功
//                        return ResponseEntity.ok("文件上传开始");
//
//                    } else {
//                        return ResponseEntity.ok("视频名重复");
//                    }
//
//
//                } catch (IOException e) {
//                    // 记录详细的异常信息
//                    System.err.println("处理视频文件过程中出现异常，详细信息：" + e.getMessage());
//                    // 返回500状态码表示服务器内部错误
//                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("视频文件处理出现问题");
//                }
//            }
//        }
//        // 授权验证不通过
//        return ResponseEntity.ofNullable("请登录后操作");
//    }

}
